package com.cetcs.kmga.dataManager.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.net.InetAddress;
import java.util.StringTokenizer;

/**
 * 验证ip地址工具类
 * 主要测试IP地址是否能访问
 *
 * @author xutao
 * @version V1.0 创建时间：2017-02-17 16:48
 *          Copyright 2017 by CETC
 */
public class CheckIpUtil {

    private static Log LOGGER = LogFactory.getLog(CheckIpUtil.class);
    /**
     * 超时应该在3钞以上
     */
    private static final int timeOut = 3000;

    /**
     * 验证IP地址是否能连通
     *
     * @param ip
     * @return
     * @author xutao
     * @datetime 2017-02-17 17:12
     */
    public static boolean isPing(String ip) {
        //连接状态
        boolean status = false;
        //尝试是否能连同
        try {
            status = InetAddress.getByName(ip).isReachable(timeOut);
        } catch (IOException e) {
            LOGGER.error("ip地址不能ping通" + e);
        }
        return status;
    }


    /**
     * 验证IP地址的有效性
     *
     * @param ipAddr
     * @return
     * @author xutao
     * @datetime 2017-02-22 15:28
     */
    public static boolean isIpValid(String ipAddr) {
        String[] ipStr = new String[4];
        int[] ipb = new int[4];
        StringTokenizer tokenizer = new StringTokenizer(ipAddr, ".");
        int len = tokenizer.countTokens();

        if (len != 4) {
            return false;
        }
        try {
            int i = 0;
            while (tokenizer.hasMoreTokens()) {
                ipStr[i] = tokenizer.nextToken();
                ipb[i] = (new Integer(ipStr[i])).intValue();

                if (ipb[i] < 0 || ipb[i] > 255) {
                    return false;
                }
                i++;
            }
            if (ipb[0] > 0) {
                return true;
            }
        } catch (Exception e) {
            LOGGER.error("ip地址不能ping通" + e);
        }
        return false;
    }
}
